<?php

namespace app\index\controller;

use app\admin\library\Auth;
use app\common\controller\Frontend;
use EasyWeChat\Factory;
use app\admin\model\Admin;
use app\common\controller\Api;
use app\admin\model\finance\extract\Week;
use app\admin\model\finance\extract\Weeklog;
use app\admin\model\finance\extract\Books as book;
use think\Cookie;
//派讲师
class Lecturers extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
   /**
     * 公共
     * @author gzy
     * @date   2018年8月12日 09:15:00
     */
    public function _initialize(){
        parent::_initialize();
        $Api = new Api();
        //获取默认值
        $this->config = $Api->getConfig($Api->getDefault('Plan'));
        $this->config['oauth']['callback'] = "http://oa.fc62.com/index/lecturers/login";
        $this->auth = \app\admin\library\Auth::instance();
        $this->model = new Week();
        $this->Booksmodel = new book();
        $this->actionName = 'lecturers';
        //退出
        //print_r($this->auth->logout());die; 
        //模拟登陆
       // $this->auth->IndexLogin('GaoZhenYu');
        //判断权限
        //print_r($this->auth->check('see/index'));die;
        if (!$this->auth->isLogin() || (!$this->auth->isLogin() && !ValueExists($this->request->action(),'login,oauth,index'))){
            header("Location:".$this->request->domain().'/index/'.$this->actionName.'/login');
            //return redirect($this->request->domain().'/index/plan/login');
        }else{
              if(!ValueExists($this->auth->userid,config('site.SendLecturers_Leader'),'|')) $this->error(__('您没有权限'));
        
             // print_r(date('W',strtotime('2019-11-25')));die;
        }
          $start_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['start_time'];
          $end_time = GenerateDate(\think\Config::get('finance.Generate_Week'))['end_time'];
          $this->view->assign("DefaultsTime", $start_time.','.$end_time);
          $this->view->assign("DefaultsDate", date('Y'));
          $this->view->assign("DefaultsDateM", date('m'));
           $this->view->assign("DefaultsDateW", GetYearWeekOne(date('Y'),$start_time)-1);       
          $this->view->assign("DefaultsDateD", date('w')-1);
      }

   
    public function index(){
       $this->auth->logout();
       // 检测是否需要验证登录
       return redirect($this->request->domain().'/index/'.$this->actionName.'/login');
        
    }  
    public function lists() {
       header('Access-Control-Allow-Credentials:true');
       $this->view->assign('info','');
       $app = Factory::work($this->config);
      // $app->jssdk->setUrl("http://oa.fc62.com");
        $json = $app->jssdk->buildConfig(array('checkJsApi','selectEnterpriseContact','openEnterpriseChat','getLocation'));
       $this->view->assign("json", $json);
       return $this->view->fetch();
    }
    public function lists_ajax(){
       header('Access-Control-Allow-Credentials:true');
        if ($this->request->isAjax()){
            $where = ' status not in(-1,0,1)';
            $sort = $this->request->get("sort", "start_time");
            $order = $this->request->get("order", "desc");
            $page = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $offset = $limit*$page;
            $time = $this->request->get("time", '');
            $year = $this->request->get("year", '');
            if($time){
                $time = explode(',', $time);
                $where .=" and `start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
            }
            if($year){
                $where .=" and `year` = '".$year."' ";
            }
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                 ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            $list = collection($list)->toArray();
        
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }   
   
     public function edit($ids = NULL){
      header('Access-Control-Allow-Credentials:true');
      $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
      if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params['z_publish']  = \think\Session::get('admin')['userid'];
                try {
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                       $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }

    public function send(){
      header('Access-Control-Allow-Credentials:true');
      if ($this->request->isPost()) {
            $where = " status = 2 and lecturer_id <> '' ";
            $time = $this->request->post("time", '');
            $year = $this->request->post("year", '');
            if($time){
                $week = explode(',', $time);
                $where .=" and `start_time` = '".$week[0]."' and `end_time` = '".$week[1]."'";
            }else{
                 $this->error("参数错误,请稍后重试");
            }
            if($year){
                $where .=" and `year` = '".$year."' ";
            }else{
                 $this->error("参数错误,请稍后重试");
            }
            $list = $this->model
                ->where($where)
                ->select();
            $list = collection($list)->toArray();
            if(!$list) $this->error("本周还没有派讲师!");
            $time = date('m-d',strtotime($week[0])).'至'.date('m-d',strtotime($week[1])); 
            $week_n = GetYearWeekOne(date('Y',strtotime($week[0])),$week[0]);
            $time_h = "第".$week_n."周（".$time."）会议，";
            foreach ($list as $key => $value) {
               $info =  $this->send_lecturer($time_h,$value);
            }
            $this->success("操作成功");
        }
        $this->error("参数错误,请稍后重试");
    }
    // 给老师的通知：
// 陈丽萍老师您好，总部已派您参加黑龙江分公司第47周（12-1至12-7）会议，会议地点北京，请做好准备工作；

// 给分公司负责人的通知：
// XXX你好，总部已派XXX老师参加你公司第47周（12-1至12-7）会议，请做好接待工作；

// 给其他人通知：
// XXX你好，总部已派XXX老师参加黑龙江分公司第47周（12-1至12-7）会议，请知悉；

// 其他人：刘副总，审佳美，王海涛，黄丽丽
    public function send_lecturer($time_h = null,$value = []){

            //老师名称
           $lecturer_name = '$userName='.$value['lecturer_id'].'$老师';

            //分公司名称
           $department_name = '$departmentName='.$value['department'].'$';
           //给老师 start
           $lecturer_content =  $lecturer_name.'您好，总部已派您参加'.$department_name.$time_h.'会议地点:'.$value['address'].'，请做好准备工作。';
           pushMsgText($this->config,"text",array("content"=>$lecturer_content),$value['lecturer_id'],'','',0,1);
           //end
           //分公司负责人 start
           $userList = TableListSqlQuery('Admin',"find_in_set('".$value['department']."',department) and `isleader` = '1'",'userid');
           $userList = array_column($userList,'userid');
           if($userList){
            //负责人名称
            $isleader_name = '$userName='.$userList[0].'$您好，';
            //给负责人
            $isleader_content =  $isleader_name.'总部已派'.$lecturer_name.'参加您公司'.$time_h.'请做好接待工作。';
            pushMsgText($this->config,"text",array("content"=>$isleader_content),$userList[0],'','',0,1);
          }
          //end
           //其他人 start
           $SomeoneElse = explode('|',config('site.SendLecturers_SomeoneElse'));
           foreach ($SomeoneElse as $k => $v) {
              $Someone_content = '$userName='.$v.'$您好，总部已派'.$lecturer_name.'参加'.$department_name.$time_h.'请知悉。';
              pushMsgText($this->config,"text",array("content"=>$Someone_content),$v,'','',0,1);
           }
        return true;
    }
    public function login(){
        $app = Factory::work($this->config);
        $token = $app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    //print_r(\think\Session::get('admin')['userid']);die;
                    return redirect($this->request->domain().'/index/'.$this->actionName.'/lists');
                }
            }
        }else{
            return redirect($this->request->domain().'/index/'.$this->actionName.'/oauth');
        }
    }
   public function oauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->config['corp_id']."&redirect_uri=".$this->config['oauth']['callback']."&response_type=code&scope=".$this->config['oauth']['scopes']."&agentid=".$this->config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

  

}
